﻿using System;
using System.Collections.Generic;
using System.IO;

using RexToy.Resources;
using RexToy.UI.WinForm.Pmlx;

namespace RexToy.UI.WinForm.Controls
{
    public class Icon : IStaticResource
    {
        private System.Drawing.Icon _icon;
        public void InitializeUri(string uri, PmlxDoc doc)
        {
            PrefixedName pName = new PrefixedName(uri);
            ITargetLocator locator = LocatorFactory.Create(doc.GetNamespaceOfPrefix(pName.Prefix));
            using (Stream stream = locator.GetStream(pName.LocalName))
            {
                _icon = new System.Drawing.Icon(stream);
            }
        }

        public string Key { get; set; }

        public object Target
        {
            get
            {
                if (_icon == null)
                    ExceptionHelper.ThrowResourceNotLoadYet();
                return _icon;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~Icon()
        {
            Dispose(false);
        }

        private bool _disposed;
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                _icon.Dispose();
            }

            _disposed = true;
        }
    }
}
